package com.eight.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * @author 向文豪
 * @program: eight-education-parent
 * @description:
 * @date 2023/5/28 19:21
 */
@Component
public class OssUtil {
    public static String uploadFile(MultipartFile file){
        String filename = file.getOriginalFilename();
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5t7qT3QFtqt92vDA81LV";
        String accessKeySecret = "PWICuPYZBexMoZy5EjuOCM9pWGzQZs";
        String bucketName = "qy8group";
        String objectName = UUID.randomUUID() + filename;
        OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
        String src = "https://" + bucketName + "." + endpoint + "/" + objectName;

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            ossClient.putObject(putObjectRequest);
        } catch (OSSException var17) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + var17.getErrorMessage());
            System.out.println("Error Code:" + var17.getErrorCode());
            System.out.println("Request ID:" + var17.getRequestId());
            System.out.println("Host ID:" + var17.getHostId());
        } catch (Exception var18) {
            System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
            System.out.println("Error Message:" + var18.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }

        }
        return src;
    }

}
